#import "RNToolbarButton.h"
#import "RNLayoutHelper.h"


//NSString* const RNToolbarItemViewLayoutHelperKey = @"layoutHelper";
NSString* const RNToolbarButtonIdentifierKey = @"RNToolbarButtonIdentifierKey";
NSString* const RNToolbarButtonToolbarKey = @"RNToolbarButtonToolbarKey";

@interface RNToolbarButton (RNToolbarItemView)
-(void)initialize_;
@end


@implementation RNToolbarButton

@synthesize layoutHelper = layoutHelper_;
@synthesize toolbar = toolbar_;
@synthesize identifier = identifier_;

+(RNToolbarButton *)flexibleSpaceButton {
    RNToolbarButton *flexibleSpace = [[self alloc] initWithIdentifier:RNToolbarFlexibleSpaceButtonIdentifier withTitle:nil withImageNamed:nil withAction:nil];
    [[flexibleSpace layoutHelper] setHeightType:RNSizeFill];
    [[flexibleSpace layoutHelper] setWidthType:RNSizeFill];
    return flexibleSpace;
}

-(id)initWithIdentifier:(NSString *)identifier withTitle:(NSString *)title withImageNamed:(NSString *)imageName withAction:(SEL)action {
    if (!(self = [super initWithFrame:NSZeroRect]))
        return nil;
    [self setIdentifier:identifier];
    [self setTitle:title];
    [self setImage:[NSImage imageNamed:imageName]];
    [self setAction:action];
    [self initialize_];
    return self;
}

-(id)initWithFrame:(NSRect)frameRect {
    return [self initWithIdentifier:nil withTitle:nil withImageNamed:nil withAction:NULL];
}

-(void)initialize_ {
    [self setBordered:NO];
    [self setBezelStyle:NSRegularSquareBezelStyle];
    [self setButtonType:NSMomentaryChangeButton];
    [self setAutoresizesSubviews:NO];
    [self setAutoresizingMask:NSViewNotSizable];
    [self setLayoutHelper:[[RNLayoutHelper alloc] initWithView:self]];
    [[self layoutHelper] setHeightType:RNSizeFixed];
    [[self layoutHelper] setWidthType:RNSizeFixed];
    [[self layoutHelper] setHorizontalLayoutType:RNHorizontalLeft];
    [[self layoutHelper] setVerticalLayoutType:RNVerticalCenter];
}
    
-(void)encodeWithCoder:(NSCoder *)theCoder {
    [super encodeWithCoder:theCoder];
    
//    [theCoder encodeObject:[self layoutHelper] forKey:RNToolbarItemViewLayoutHelperKey];
    [theCoder encodeObject:[self identifier] forKey:RNToolbarButtonIdentifierKey];
    [theCoder encodeConditionalObject:[self toolbar] forKey:RNToolbarButtonToolbarKey];
}

-(id)initWithCoder:(NSCoder *)theCoder {
    if (!(self = [super initWithCoder:theCoder]))
        return nil;
    [self setIdentifier:[theCoder valueForKey:RNToolbarButtonIdentifierKey]];
    [self setToolbar:[theCoder valueForKey:RNToolbarButtonToolbarKey]];
    [self initialize_];
    return self;
}

-(void)setTitle:(NSString *)title {
    [super setTitle:title];
    [self sizeToFit];
    [[[self toolbar] layoutHelper] tile];
}

-(NSView<RNLayoutView> *)parent {
    if ([[self superview] conformsToProtocol:@protocol(RNLayoutView)])
        return (NSView<RNLayoutView> *)[self superview];
    return nil;
}

-(NSArray *)children {
    return nil;
}

@end
